package com.ewili.x.special.service.data.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ewili.framework.utils.ExceptionUtils;
import com.ewili.x.special.dao.inter.StockDao;
import com.ewili.x.special.entity.Stock;
import com.ewili.x.special.service.data.inter.StockService;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author wonder
 */
@Service
public class StockServiceImpl implements StockService {

    @Autowired
    private StockDao stockDao;

    @Override
    public void spideStock() {
        String baseUrl = "http://19.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112403971510070694685_1600147965999&pn=1&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:13,m:0+t:80,m:1+t:2,m:1+t:23&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152&_=1600147966026";
        Integer pageNums = this.getUrlPageNums(baseUrl);
        if (pageNums == 0) {
            return;
        }
        for (int i = 1; i <= pageNums; i++) {
            String stockListUrl = "http://19.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112403971510070694685_1600147965999&pn=" + i + "&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:13,m:0+t:80,m:1+t:2,m:1+t:23&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152&_=1600147966026";
            spide(stockListUrl);
        }


    }

    @Override
    public String getCodeFromUrl(String url, String start, String end, boolean clearMarket) {
        String temp = StringUtils.remove(url, start);
        temp = StringUtils.remove(temp, end);
        if (clearMarket) {
            temp = StringUtils.replace(temp, "sz|sh", "");
        }
        return temp;
    }

    /**
     * 获取Url的页数
     *
     * @return
     */
    private Integer getUrlPageNums(String baseUrl) {
        String baseContent = this.getContent(baseUrl);
        String subContent = StringUtils.substringBetween(baseContent, "\"total\":", ",\"diff\":");
        Integer totalStocks = Integer.valueOf(subContent);
        return Math.abs(totalStocks / 20 + 1);
    }

    private void spide(String url) {
        String content = this.getContent(url);
        String subContent = StringUtils.substringBetween(content, "(", ")");
        JSONObject jsonObject = JSONUtil.parseObj(subContent);
        JSONObject dataObject = jsonObject.getJSONObject("data");
        JSONArray diffArr = dataObject.getJSONArray("diff");
        for (int i = 0; i < diffArr.size(); i++) {
            JSONObject object = diffArr.getJSONObject(i);
            String code = object.getStr("f12");
            String chName = object.getStr("f14");
            String market = code.startsWith("6") ? "sh" : "sz";
            Double newestPrice = object.getDouble("f2");
            Double upDownRate = object.getDouble("f3");
            Double amount = object.getDouble("f6");
            Double exchangeRate = object.getDouble("f8");
            Double pe = object.getDouble("f9");
            Double pb = object.getDouble("f23");

            Stock stock = stockDao.findByCode(code);

            if (stock == null) {
                stock = new Stock();
            }

            stock.setCode(code);
            stock.setAmount(amount);
            stock.setExchangeRate(exchangeRate);
            stock.setChName(chName);
            stock.setMarket(market);
            stock.setNewestPrice(newestPrice);
            stock.setUpDownRate(upDownRate);
            stock.setPb(pb);
            stock.setPe(pe);

            stockDao.save(stock);
        }
    }


    private String getContent(String url) {
        Connection conn = Jsoup.connect(url).timeout(10000000).ignoreContentType(true);
        String content = "";
        try {
            content = conn.get().toString();
        } catch (IOException e) {
            ExceptionUtils.propagate(e);
        }

        if (!StringUtils.contains(content, "total")) {
            return null;
        }
        return content;
    }


}
